package com.phonetools.commonutils.security

import java.security.GeneralSecurityException
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec
import javax.crypto.spec.IvParameterSpec

/**
算法:DES
模式:EBC、CBC、PCBC、CTR、CTS、CFB、CFB8~128、OFB、OFB8~128
填充:NoPadding、PKCS5Padding、PKCS7Padding、ISO10126Padding
例:DES/CBC/PKCS7Padding
 * */

/*fun main{
    val desContent = "des CBC加密"
    val desKey = "12345678"
    val desEncrypt = desEncrypt("DES/CBC/PKCS5Padding", desContent.toByteArray(), desKey.toByteArray())
    Log.d(TAG, "desEncrypt=${desEncrypt.toHex()}")
    val desDecrypt = desDecrypt("DES/CBC/PKCS5Padding", desEncrypt, desKey.toByteArray())
    Log.d(TAG, "desDecrypt=${desDecrypt.toString(Charsets.UTF_8)}")
}*/

private val algorithm = "DES"

/**
 * DES加密，
 * @param mode 算法/模式/填充
 * @param content 待加密内容
 * @param desKey key
 * @return ByteArray
 * */
@Throws(GeneralSecurityException::class)
fun desEncrypt(
    mode: String, content: ByteArray, desKey: ByteArray
): ByteArray {
    try {
        val cipher = Cipher.getInstance(mode)
        val kf = SecretKeyFactory.getInstance(algorithm)
        val keySpe = DESKeySpec(desKey)
        val key: Key = kf.generateSecret(keySpe)
        val iv = IvParameterSpec(desKey)
        cipher.init(Cipher.ENCRYPT_MODE, key, iv)
        return cipher.doFinal(content)
    } catch (e: Exception) {
        throw GeneralSecurityException(e)
    }
}

/**
 * AES解密，
 * @param mode 算法/模式/填充
 * @param content 待加密内容
 * @param desKey key
 * @return ByteArray
 * */
@Throws(GeneralSecurityException::class)
fun desDecrypt(
    mode: String, content: ByteArray, desKey: ByteArray
): ByteArray {
    try {
        val cipher = Cipher.getInstance(mode)
        val kf = SecretKeyFactory.getInstance(algorithm)
        val keySpe = DESKeySpec(desKey)
        val key: Key = kf.generateSecret(keySpe)
        val iv = IvParameterSpec(desKey)
        cipher.init(Cipher.DECRYPT_MODE, key, iv)
        return cipher.doFinal(content)
    } catch (e: Exception) {
        throw GeneralSecurityException(e)
    }
}